import React, { useState } from 'react';
import { Modal, Button, message, Spin, Alert } from 'antd';
import { 
  EyeOutlined, 
  DownloadOutlined, 
  CloseOutlined,
  FileWordOutlined,
  FilePdfOutlined,
  FilePptOutlined,
  FileExcelOutlined
} from '@ant-design/icons';
import FileViewer from 'react-file-viewer';
import './FileViewer.scss';

const CustomFileViewer = ({ 
  visible, 
  onClose, 
  fileUrl, 
  fileName, 
  fileType,
  onError 
}) => {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 获取文件类型
  const getFileType = (fileName) => {
    const extension = fileName.split('.').pop().toLowerCase();
    const typeMap = {
      'pdf': 'pdf',
      'doc': 'docx',
      'docx': 'docx',
      'xls': 'xlsx',
      'xlsx': 'xlsx',
      'ppt': 'pptx',
      'pptx': 'pptx',
      'txt': 'txt',
      'csv': 'csv'
    };
    return typeMap[extension] || extension;
  };

  // 获取文件图标
  const getFileIcon = (type) => {
    const iconMap = {
      'pdf': <FilePdfOutlined style={{ color: '#f5222d', fontSize: 24 }} />,
      'docx': <FileWordOutlined style={{ color: '#1890ff', fontSize: 24 }} />,
      'doc': <FileWordOutlined style={{ color: '#1890ff', fontSize: 24 }} />,
      'xlsx': <FileExcelOutlined style={{ color: '#52c41a', fontSize: 24 }} />,
      'xls': <FileExcelOutlined style={{ color: '#52c41a', fontSize: 24 }} />,
      'pptx': <FilePptOutlined style={{ color: '#fa8c16', fontSize: 24 }} />,
      'ppt': <FilePptOutlined style={{ color: '#fa8c16', fontSize: 24 }} />
    };
    return iconMap[type] || <EyeOutlined style={{ fontSize: 24 }} />;
  };

  const handleError = (error) => {
    console.error('文件预览错误:', error);
    setError('文件预览失败，可能是文件格式不支持或文件损坏');
    setLoading(false);
    onError && onError(error);
  };

  const handleLoad = () => {
    setLoading(false);
    setError(null);
  };

  const handleDownload = () => {
    if (fileUrl) {
      const link = document.createElement('a');
      link.href = fileUrl;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('文件下载开始');
    }
  };

  const renderFileViewer = () => {
    if (!fileUrl || !fileName) {
      return (
        <Alert
          message="文件信息不完整"
          description="缺少文件URL或文件名"
          type="warning"
          showIcon
        />
      );
    }

    const type = getFileType(fileName);
    
    // 支持的文件类型
    const supportedTypes = ['pdf', 'docx', 'doc', 'xlsx', 'xls', 'pptx', 'ppt', 'txt', 'csv'];
    
    if (!supportedTypes.includes(type)) {
      return (
        <Alert
          message="不支持的文件类型"
          description={`当前不支持预览 .${type} 格式的文件，请下载后查看`}
          type="info"
          showIcon
          action={
            <Button size="small" onClick={handleDownload}>
              下载文件
            </Button>
          }
        />
      );
    }

    return (
      <div className="file-viewer-container">
        {loading && (
          <div className="loading-overlay">
            <Spin size="large" />
            <p>正在加载文件...</p>
          </div>
        )}
        
        {error && (
          <Alert
            message="预览失败"
            description={error}
            type="error"
            showIcon
            action={
              <Button size="small" onClick={handleDownload}>
                下载文件
              </Button>
            }
          />
        )}

        {!error && (
          <FileViewer
            fileType={type}
            filePath={fileUrl}
            onError={handleError}
            onLoad={handleLoad}
            key={fileUrl} // 强制重新渲染
          />
        )}
      </div>
    );
  };

  return (
    <Modal
      title={
        <div className="file-viewer-header">
          <div className="file-info">
            {getFileIcon(getFileType(fileName))}
            <span className="file-name">{fileName}</span>
          </div>
        </div>
      }
      open={visible}
      onCancel={onClose}
      width="90%"
      style={{ top: 20 }}
      bodyStyle={{ 
        height: 'calc(100vh - 200px)', 
        padding: 0,
        overflow: 'hidden'
      }}
      footer={[
        <Button key="download" icon={<DownloadOutlined />} onClick={handleDownload}>
          下载
        </Button>,
        <Button key="close" onClick={onClose}>
          关闭
        </Button>
      ]}
      destroyOnClose
    >
      {renderFileViewer()}
    </Modal>
  );
};

// 文件预览触发器组件
export const FileViewerTrigger = ({ 
  fileUrl, 
  fileName, 
  children, 
  buttonProps = {} 
}) => {
  const [visible, setVisible] = useState(false);

  const handlePreview = () => {
    if (!fileUrl) {
      message.error('文件URL不存在');
      return;
    }
    setVisible(true);
  };

  const handleError = (error) => {
    message.error('文件预览失败');
  };

  return (
    <>
      {children ? (
        <div onClick={handlePreview} style={{ cursor: 'pointer' }}>
          {children}
        </div>
      ) : (
        <Button 
          icon={<EyeOutlined />} 
          onClick={handlePreview}
          {...buttonProps}
        >
          预览
        </Button>
      )}
      
      <CustomFileViewer
        visible={visible}
        onClose={() => setVisible(false)}
        fileUrl={fileUrl}
        fileName={fileName}
        onError={handleError}
      />
    </>
  );
};

export default CustomFileViewer;